package com.appspot.mscheckers;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelPresence;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.gson.Gson;

public class ConnectedHandler extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		ChannelPresence presence = channelService.parsePresence(req);
		String userId = presence.clientId();

		User user = Checkers.inSignIn.get(userId);
		User u = EMF.getUser(userId);
		if( u == null ){
			EMF.insert(user);
		}else{
			user.setUser(u);
			EMF.update(user);
		}
		
		if( user != null ){			
			//send a note to all connected users
			Enumeration<String> keys = Checkers.userMap.keys();
			String key;
			String message = "{\""+Constant.MESSAGE_TYPE+"\":\""+Constant.USER_SIGNIN+"\"}";
			Gson gson = new Gson();
			String gsu = gson.toJson(user);
			
			while(keys.hasMoreElements()){
				key = keys.nextElement();
				if( key.equals("123321")) continue;
				try{
					channelService.sendMessage(new ChannelMessage(key, message));
					channelService.sendMessage(new ChannelMessage(key, gsu));
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			Checkers.inSignIn.remove(userId);
			Checkers.userMap.put(userId, user);
		}
	}
	
}
